package com.cwvs.dao;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;

import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import com.cwvs.models.ResultInfo;
import com.cwvs.utils.CommonUtils;
import com.cwvs.utils.DateUtils;

/**
 * 
 * 短信相关DAO
 */
@Repository
public class AppSmsDao {
	@Resource
	private JdbcTemplate jdbcTemplate;

	/**
	 * 短信新增
	 */
	public ResultInfo saveAppSms(Map<String, Object> o) {
		ResultInfo res = new ResultInfo();
		res.setResCode("0");
		res.setMessage("短信发送失败");
		if (StringUtils.isBlank(MapUtils.getString(o, "PHONE"))) {
			res.setMessage("请输入手机号");
			return res;
		}
		if (!CommonUtils.checkMemberMobilePhone(MapUtils.getString(o, "PHONE"))) {
			res.setMessage("请输入正确的手机号");
			return res;
		}
		String validate = MapUtils.getString(o, "VALIDATE");
		// 生成短信发送token
		String token = UUID.randomUUID().toString();
		StringBuffer sbf = new StringBuffer();
		sbf.append(" INSERT INTO APP_SMS(ID,PHONE,VALIDATE,CTIME,ETIME)");
		sbf.append(" VALUES (?,?,?,?,?)");
		List<Object> params = new ArrayList<Object>();
		params.add(token);
		params.add(MapUtils.getString(o, "PHONE"));
		params.add(validate);
		params.add(DateUtils.DateToLong14(new Date()));
		params.add(DateUtils.DateToLong14(new Date(
				new Date().getTime() + 30 * 60 * 1000)));
		int count = jdbcTemplate.update(sbf.toString(), params.toArray());
		if (count > 0) {
			ResultInfo r= CommonUtils.sendSms(MapUtils.getString(o, "PHONE"), "20987", new String[]{validate,"30"});
			res.setSuccess(r.isSuccess());
			res.setResult(token);
			res.setMessage(r.getMessage());
			return res;
		}
		return res;
	}

	/***
	 * 通过token获取短信信息
	 * 
	 * @param token
	 * @return
	 */
	public ResultInfo getAppSmsByToken(String token) {
		ResultInfo res = new ResultInfo();
		res.setMessage("无效的TOKEN");
		res.setResCode("0");
		if (StringUtils.isBlank(token)) {
			return res;
		}
		StringBuffer sbf = new StringBuffer();
		sbf.append(" SELECT PHONE,VALIDATE,CTIME,ETIME FROM APP_SMS ");
		sbf.append(" WHERE ID=? ");
		List<Map<String, Object>> ls = jdbcTemplate.queryForList(
				sbf.toString(), new Object[] { token });
		if (ls.isEmpty()) {
			return res;
		}
		res.setResult(ls.get(0));
		res.setSuccess(true);
		return res;
	}
}
